from itsdangerous import TimedJSONWebSignatureSerializer, BadData
from django.conf import settings

from django.contrib.auth.models import AbstractUser
from django.db import models
from . import constants

# Create your models here.
class User(AbstractUser):
    """用户模型类"""
    mobile = models.CharField(max_length=11, unique=True, verbose_name='手机号')
    email_active = models.BooleanField(default=False, verbose_name="邮箱验证状态")

    class Meta:
        db_table = 'tb_users'
        verbose_name = '用户'
        verbose_name_plural = verbose_name

    def generate_email_verify_url(self):
        serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, constants.EMAIL_USER_VERIFY_EXPIRES)
        payload = {
            "user_id": self.id,
            "email": self.email
        }
        token = serializer.dumps(payload).decode()
        verify_url = "http://www.meiduo.site:8080/success_verify_email.html?token=" + token
        return verify_url

    @staticmethod
    def check_email_binding(token):
        serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, constants.EMAIL_USER_VERIFY_EXPIRES)
        try:
            payload = serializer.loads(token)
        except BadData:
            return None
        else:
            user_id = payload.get("user_id")
            email = payload.get("email")
            try:
                user = User.objects.get(id=user_id, email=email)
            except User.DoesNotExist:
                return None
            else:
                return user
